package com.greatchn.authorization_server.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @AccessTokenConverter: jwt 拓展
 * @author: ZBoHang
 * @time: 2023/3/2 15:15
 */
@Component
public class AccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

        Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();

        User principal = (User) currentAuthentication.getPrincipal();

        String username = principal.getUsername();

        Collection<GrantedAuthority> authorities = principal.getAuthorities();

        Map<String, String> payLoadMap = (Map<String, String>) super.convertAccessToken(token, authentication);

        payLoadMap.put("userName", username);
        payLoadMap.put("customerAuthorities", authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining("|")));

        return payLoadMap;
    }
}
